package br.com.spam.pipeline.iu;

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import br.com.spam.pipeline.core.MemoryPosition;

public class IU_Memory extends JPanel
{
	private static final long serialVersionUID = -9186234586224408248L;

	private IU_Datashow parent;

	private JLabel title = new JLabel("Memória recentemente usada", (int) CENTER_ALIGNMENT);
	private JLabel address = new JLabel("Endereço", (int) CENTER_ALIGNMENT);
	private JLabel value = new JLabel("Valor", (int) CENTER_ALIGNMENT);
	private JTextField[] addresses = new JTextField[4];
	private JTextField[] values = new JTextField[4];

	public IU_Memory(IU_Datashow parent)
	{
		this.parent = parent;

		this.setLayout(new BorderLayout());
		this.add(this.title, BorderLayout.NORTH);
		this.title.setBorder(BorderFactory.createLineBorder(Color.BLACK));

		JPanel p = new JPanel();
		this.add(p, BorderLayout.CENTER);
		p.setLayout(new BorderLayout());
		p.setBorder(BorderFactory.createLineBorder(Color.BLACK));

		JPanel addrAux = new JPanel();
		addrAux.setLayout(new BoxLayout(addrAux, BoxLayout.Y_AXIS));
		addrAux.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		addrAux.add(this.address);

		JPanel valueAux = new JPanel();
		valueAux.setLayout(new BoxLayout(valueAux, BoxLayout.Y_AXIS));
		valueAux.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		valueAux.add(this.value);

		p.add(addrAux, BorderLayout.WEST);
		p.add(valueAux, BorderLayout.CENTER);
		this.setUpArrays(addrAux, valueAux);
		this.update();
	}
	public void setUpArrays(JPanel addr, JPanel value)
	{
		for (int i = 0; i < 4; i++)
		{
			this.addresses[i] = new JTextField(5);
			this.values[i] = new JTextField();
			this.addresses[i].setEditable(false);
			this.values[i].setEditable(false);
			this.addresses[i].setBackground(Color.WHITE);
			this.values[i].setBackground(Color.WHITE);
			addr.add(this.addresses[i]);
			value.add(this.values[i]);
		}
	}

	public void update()
	{
		if (this.parent.pipeline() == null)
			return;

		MemoryPosition[] mp = this.parent.pipeline().getRecentUsedMemory();
		for (int i = 0; i < 4; i++)
		{
			this.values[i].setText(this.getMemoryAsString(mp[i]));
			this.addresses[i].setText(String.valueOf(mp[i].getAddress()));
		}
	}

	private String getMemoryAsString(MemoryPosition memory)
	{
		return String.format("%1$x (%1$d)", memory.getData());
	}
}
